let ctx, subsystems;

let addresses=[];

export default {
    listen(eventDef, name){
        if (typeof addresses[eventDef.address] !== "undefined") {
            console.warn("already listen this address?");
            console.trace();
        }
        addresses[eventDef.address]=name;
        return {address:eventDef.address};
    },
    unlisten(eventObj){
        delete addresses[eventObj.opts.addresses];
    },
    async init(_ctx, _subsystems){
        ctx=_ctx; subsystems=_subsystems;
        ctx.app.all("/i/*", (req,res)=>{
            console.log("all addresses:",addresses);
            let rreq={body:req.body};
            let rres={json:(...args)=>res.json.call(res,...args), send:(...args)=>res.json.send(res,...args)};
            let eName=addresses[req.params[0]];
            console.log(`network access ${req.params[0]} -> ${eName}`);
            subsystems.events.trigger(eName,rreq,rres);
        });
        let networks = await subsystems.db.Events.getAll({type: "network"});
        for (let eventObj of networks) {
            console.log(`saved network handler ${eventObj.name}, address:${eventObj.opts.address}`);
            addresses[eventObj.opts.address]=eventObj.name;
        }
    }
}